<template>
  <div class="borrow-manage">
    <!-- 查询/筛选条件 -->
    <el-form :inline="true" :model="queryParams" class="query-form" @submit.prevent="getList">
      <el-form-item label="借用人">
        <el-input v-model="queryParams.userName" placeholder="请输入借用人姓名" clearable @keyup.enter="getList"/>
      </el-form-item>
      <el-form-item label="资产名称">
        <el-input v-model="queryParams.assetName" placeholder="请输入资产名称" clearable @keyup.enter="getList"/>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryParams.borrowStatus" placeholder="请选择状态" clearable @change="getList">
          <el-option label="全部" value=""/>
          <el-option label="借用中" value="1"/>
          <el-option label="已归还" value="2"/>
          <el-option label="逾期" value="3"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getList">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div class="operation-buttons">
      <el-button type="success" @click="exportData" :loading="exportLoading">导出</el-button>
    </div>

    <!-- 借用记录表格 -->
    <el-table :data="borrowList" border style="width: 100%" :loading="loading">
      <el-table-column prop="borrowId" label="ID" width="80"/>
      <el-table-column prop="userName" label="借用人"/>
      <el-table-column prop="assetName" label="资产名称"/>
      <el-table-column prop="borrowTime" label="借用时间" width="160"/>
      <el-table-column prop="expectedReturnTime" label="预计归还时间" width="160"/>
      <el-table-column prop="actualReturnTime" label="实际归还时间" width="160"/>
      <el-table-column prop="borrowStatus" label="状态">
        <template #default="scope">
          <el-tag v-if="scope.row.borrowStatus === '1'" type="warning">借用中</el-tag>
          <el-tag v-if="scope.row.borrowStatus === '2'" type="success">已归还</el-tag>
          <el-tag v-if="scope.row.borrowStatus === '3'" type="danger">逾期</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button v-if="scope.row.borrowStatus === 'borrowed'" type="primary" size="small"
                     @click="handleReturn(scope.row)">归还
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:currentPage="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="margin-top: 20px; display: flex; justify-content: flex-end;"
    />
  </div>
</template>

<script setup>
import {ref, onMounted, watch} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import * as XLSX from 'xlsx';
import {adminBorrowManage} from "@/stores/admin/BorrowManage.js"; // 引入 Pinia Store

const borrowStore = adminBorrowManage();

// 从 store 中解构状态和 actions
const borrowList = ref(borrowStore.borrowList);
const total = ref(borrowStore.total);
const loading = ref(borrowStore.loading);
const queryParams = ref(borrowStore.queryParams);

const exportLoading = ref(false); // 导出按钮 loading 状态

// 获取借用记录列表
const getList = () => {
  borrowStore.getBorrowList();
};

// 重置查询条件
const resetQuery = () => {
  borrowStore.resetQueryParams();
  getList();
};

// 处理每页显示条数改变
const handleSizeChange = (val) => {
  borrowStore.setPageSize(val);
};

// 处理当前页码改变
const handleCurrentChange = (val) => {
  borrowStore.setPageNum(val);
};

// 处理归还操作
const handleReturn = async (row) => {
  const confirmResult = await ElMessageBox.confirm(
      `确定要归还资产 "${row.assetName}" 吗?`,
      '归还确认',
      {
        confirmButtonText: '确定归还',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).catch(() => {
  });

  if (confirmResult === 'confirm') {
    const success = await borrowStore.returnBorrow(row.id);
    if (success) {
      getList(); // 刷新列表
    }
  }
};


// 导出数据
const exportData = async () => {
  exportLoading.value = true;
  try {
    const allQueryParams = {...queryParams.value};
    allQueryParams.pageNum = undefined; // 导出所有数据，pageNum 和 pageSize 可以不传或置为 undefined
    allQueryParams.pageSize = undefined;

    const response = await borrowStore.getAllBorrowList(allQueryParams);
    const data = response.rows;

    if (!data || data.length === 0) {
      ElMessage.warning('没有数据可以导出');
      return;
    }

    // 将数据转换为 Excel 格式
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.json_to_sheet(data);
    XLSX.utils.book_append_sheet(wb, ws, '借用记录');

    // 导出 Excel 文件
    XLSX.writeFile(wb, 'borrow_records.xlsx');

  } catch (error) {
    console.error('导出数据失败:', error);
    ElMessage.error('导出数据失败');
  } finally {
    exportLoading.value = false;
  }
};

onMounted(() => {
  getList(); // 页面加载时获取列表
});
</script>

<style scoped>
.borrow-manage {
  padding: 20px;
}

.query-form {
  margin-bottom: 20px;
}

.operation-buttons {
  margin-bottom: 20px;
}
</style>